package com.example.stock.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.stock.business.WuguBusiness;
import com.example.stock.controller.dto.WuguDTO;
import com.example.stock.excel.download.WuguExcel;
import com.example.stock.service.WuguService;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = "*")
@RequestMapping("wugu")
@RestController
public class WuguController {

    @Autowired
    WuguBusiness wuguBusiness;

    @Autowired
    WuguService wuguService;


    @GetMapping()
    public Result index() {
        return ResultGenerator.genSuccessResult(wuguBusiness.getWuguDTO());
    }

    @GetMapping("history")
    public Result history() {
        return ResultGenerator.genSuccessResult(wuguService.getWuguHistories());
    }

    @GetMapping("history/{stock}")
    public Result history(@PathVariable String stock) {
        return ResultGenerator.genSuccessResult(wuguService.getWuguHistory(stock));
    }

    /**
     * 导出吾股 excel
     */
    @SneakyThrows(IOException.class)
    @GetMapping("export")
    public void exportWugu(HttpServletResponse response) {
        setExcelRespProp(response,"吾股数据");

        List<WuguDTO> wugu = wuguBusiness.getWuguDTO();
        List<WuguExcel> ret = new ArrayList<>();
        wugu.forEach(item -> {
            WuguExcel wuguExcel = new WuguExcel();
            BeanUtils.copyProperties(item, wuguExcel);
            ret.add(wuguExcel);
        });

        EasyExcel.write(response.getOutputStream())
                .head(WuguExcel.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("吾股数据")
                .doWrite(ret);
    }

    private void setExcelRespProp(HttpServletResponse response,  String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
